#include"main_server.h"


// 两个队列的声明
thread_queue<lars::ReportStatusRequest>* report_queue = NULL;
thread_queue<lars::GetRouteRequest>* dns_queue = NULL;

// 给每一个agent udp server 定义一个route_lb
route_lb* r_lb[3];

// 定义全局变量，用于存放一些参数
struct data_config config;

void init_lb_agent(){
    // 1.加载配置文件
    config_file::setPath("./conf/agent.conf");
    config.udp_server_cnt = config_file::instance()->GetNumber("agent", "udp_server_cnt", 5);
    config.udp_server_ip = config_file::instance()->GetString("agent", "ip", "0.0.0.0");       

    config.dns_ip = config_file::instance()->GetString("dns", "ip", "0.0.0.0");        
    config.dns_port = config_file::instance()->GetNumber("dns", "port", 8888);  

    config.reporter_ip = config_file::instance()->GetString("reporter", "ip", "0.0.0.0");     
    config.reporter_port = config_file::instance()->GetNumber("reporter", "port", 9999);    

    config.lb_probe_num = config_file::instance()->GetNumber("loadbalance", "probe_num", 10);   
    config.lb_init_succ_cnt = config_file::instance()->GetNumber("loadbalance", "init_succ_cnt", 180);   
    config.lb_init_err_cnt = config_file::instance()->GetNumber("loadbalance", "init_err_cnt", 5);   
    config.lb_err_rate = config_file::instance()->GetFloat("loadbalance", "err_rate", 0.1);               
    config.lb_succ_rate = config_file::instance()->GetFloat("loadbalance", "succ_rate", 0.95);   
    config.lb_contin_err_limit = config_file::instance()->GetNumber("loadbalance", "contin_err_limit", 10);   
    config.lb_contin_succ_limit = config_file::instance()->GetNumber("loadbalance", "contin_succ_limit", 10);   
    config.lb_idle_timeout  = config_file::instance()->GetNumber("loadbalance", "idle_timeout", 15);
    config.lb_overload_timeout = config_file::instance()->GetNumber("loadbalance", "overload_timeout", 15);
    config.lb_update_timeout = config_file::instance()->GetNumber("loadbalance", "update_timeout", 15);

    // 2.创建与udp server个数相同的route_lb
    for(int i=0; i<config.udp_server_cnt; i++){
        int id = i+1;   // route_lb 的id是从 1 开始的
        r_lb[i] = new route_lb(id);
        if(r_lb[i] == NULL){
            fprintf(stderr, "new routr_lb(id=%d) error\n", id);
            exit(1);
        }
    }

}

int main(int argc, char** argv){
    
    init_lb_agent();

    // 1.启动UDP server服务(3个)，用来接收业务层发开的消息
    start_udp_server(NULL);

    sleep(0.1);

    // 2.启动lars_reporter线程
    report_queue = new thread_queue<lars::ReportStatusRequest>();
    if(report_queue == NULL){
        fprintf(stderr, "new report queue error\n");
        exit(1);
    }
    start_report_client(NULL);
    

    // 3.启动lars_dns线程
    dns_queue = new thread_queue<lars::GetRouteRequest>();
    if(dns_queue == NULL){
        fprintf(stderr, "new dns queue error\n");
        exit(1);
    }
    start_dns_client(NULL);
    
    // 4.主线程阻塞
    while(1){
        sleep(10);
    }


    return 0;
}